var category = "";
var eventData;
var doctor;
var starts;
var ends;
starts = $("#startTimeValue").val().substring(0, 10) + " 00:00:00";
ends = $("#endTimeValue").val().substring(0, 10) + " 23:59:59";
$(function() {
    getListInfo();
    getDoctorLists();
    $('#calendars').fullCalendar({
        header: {
            left: '',
            center: '',
            right: ''
        },
        defaultView: 'agendaDay',
        allDaySlot: false,
        selectable: true,
        selectHelper: true,
        editable: false,
        eventLimit: true,
        nowIndicator: true,
        minTime: "07:00:00",
        maxTime: "20:00:00",
        titleFormat: 'YYYY-MM-DD',
        slotDuration: "00:15:00",
        slotLabelFormat: 'HH',
        slotLabelInterval: "00:60:00",
        slotLabelFormats: 'mm',
        slotLabelIntervals: "00:15:00",
        selectMinDistance: 30,
        defaultDate: $("#startTimeValue").val().substring(0, 10),
        height: window.innerHeight - 125,
        select: function(startDate, endDate, jsEvent, view, resource) {
            var start = startDate.format('YYYY-MM-DD HH:mm:ss');
            var end = endDate.format('YYYY-MM-DD HH:mm:ss');
            var start1 = new Date(start);
            var end1 = new Date(end);
            var continued = parseInt(end1 - start1) / 1000 / 60;
            $("#startTime").val(start);
            $("#endTimeValue").val(end);
            $("#duration").val(continued);
            var docName = document.getElementById("doctorValue").value;
            eventData = start + "," + end + "," + docName
        },
        timeFormat: 'H:mm',
        slotEventOverlap: false,
        schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
        dragRevertDuration: 200,
        unselectAuto: false,
        aspectRatio: 0.6,
        events: function(start, end, timezone, callback) {
            start = starts;
            end = ends;
            doctor = document.getElementById('doctorValue').value;
            var timeSlot = start + "," + end + "," + doctor;
            $.ajax({
                url: Feng.ctxPath + '/doctorLooked/getDataListByDoctor/' + timeSlot,
                dataType: 'json',
                type: 'POST',
                success: function(data) {
                    var events = [];
                    $.each(data, function(key, value) {
                        var obj = {
                            id: value.customerId,
                            title: value.appointmentPayService,
                            start: new Date(Date.parse(value.startTime)),
                            end: new Date(Date.parse(value.endTime)),
                            customerName: value.customerName,
                            resourceId: value.id,
                            arrivalStatus: value.arrivalStatus,
                            accountarrears: value.accountarrears,
                            remarks: value.remarks
                        };
                        if (value.arrivalStatus == '1') {
                            obj.backgroundColor = "#4099ff";
                            obj.borderColor = "#4099ff"
                        } else if (value.arrivalStatus == '2') {
                            obj.backgroundColor = "#10428b";
                            obj.borderColor = "#10428b"
                        } else if (value.arrivalStatus == '3') {
                            obj.backgroundColor = "#ffba40";
                            obj.borderColor = "#ffba40"
                        } else if (value.arrivalStatus == '4') {
                            obj.backgroundColor = "#2dc87e";
                            obj.borderColor = "#2dc87e"
                        } else if (value.arrivalStatus == '5') {
                            obj.backgroundColor = "#61b740";
                            obj.borderColor = "#61b740"
                        } else if (value.arrivalStatus == '6') {
                            obj.backgroundColor = "#017cdc";
                            obj.borderColor = "#017cdc"
                        } else if (value.arrivalStatus == '7') {
                            obj.backgroundColor = "gray";
                            obj.borderColor = "gray"
                        }
                        events.push(obj)
                    });
                    callback(events)
                }
            })
        },
        eventRender: function(calEvent, element, view) {
            if (calEvent.customerName == "" || calEvent.customerName == null) {
                element.prepend("<div class='myfc-title'><span>新建预约</span></div>")
            }
        },
        eventAfterRender: function(calEvent, element, view) {
            var data3 = parseInt(calEvent.end._0 - calEvent.start._0) / 1000 / 60;
            if (element[0].clientWidth < 24) {
                element[0].innerHTML = ""
            } else if (element[0].clientWidth >= 24 && element[0].clientWidth < 45) {
                element[0].innerHTML = "";
                element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div>")
            } else {
                if (calEvent.accountarrears != 0) {
                    if (data3 < 61) {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;right: 2px;top: 1px;color: white;background: red;padding: 0 2px;border: 1px solid white;border-radius: 50%;font-size: 0.5em'>欠</div>")
                    } else {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;bottom: 5px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'>" + calEvent.remarks + "</div><div style='position: absolute;right: 2px;top: 1px;color: white;background: red;padding: 0 2px;border: 1px solid white;border-radius: 50%;font-size: 0.5em'>欠</div>")
                    }
                } else {
                    if (data3 < 61) {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div>")
                    } else {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;bottom: 5px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'>" + calEvent.remarks + "</div>")
                    }
                }
            }
        }
    });
    preloading()
});

function getListInfo() {
    $.ajax({
        url: Feng.ctxPath + "/doctorLooked/getListInfo",
        data: {
            "projectCategory": $("#projectCategory").val()
        },
        type: "POST",
        success: function(data) {
            var text = '';
            for (var i = 0; i < data.length; i++) {
                text += '<div><label style="font-weight: 500;margin:0;"><input type="checkbox" name="about" style="vertical-align: middle;margin: 0 8px 0;" value="' + data[i].projectName + '" >' + data[i].projectName + '</label></div>'
            }
            $("#projectType").html(text)
        }
    })
}

function addSet() {
    var index = layer.open({
        type: 2,
        title: '预约项目设置',
        area: ['80%', '80%'],
        fix: true,
        maxmin: true,
        content: Feng.ctxPath + '/doctorLooked/add_project'
    });
    this.layerIndex = index
}

function getDoctorLists() {
    var seleteDoctorValue = $('#doctorValue').val();
    if (seleteDoctorValue != "") {
        $("#doctor option[value='" + seleteDoctorValue + "']").attr("selected", "selected")
    }
    var seletetcName = $('#tcNameValue').val();
    if (seletetcName != "") {
        $("#fieldTc option[value='" + seletetcName + "']").attr("selected", "selected")
    }
}
checkDate = function() {
    var value = $("#startTime").val();
    doctor = document.getElementById('doctorValue').value;
    starts = value.substring(0, 10) + " 00:00:00";
    ends = value.substring(0, 10) + " 23:59:59";
    $("#startTimeValue").val(starts);
    $('#calendars').fullCalendar('gotoDate', value.substring(0, 10));
    $('#calendars').fullCalendar('refetchEvents');
    $.ajax({
        type: "POST",
        url: Feng.ctxPath + "/doctorLooked/getDoctorStatus",
        data: {
            "doctor": doctor,
            "value": value.substring(0, 10)
        },
        dataType: "json",
        success: function(data) {
            if (data == 2) {
                $('#calendars .fc-time-grid td.fc-day').css("background", "#eeeeee");
                $('#calendars .fc-time-grid').css({
                    "pointer-events": "none",
                    "cursor": "not-allowed"
                })
            } else if (data == 1) {
                $('#calendars .fc-time-grid td.fc-day').css("background", "#FFFFFF");
                $('#calendars .fc-time-grid').css({
                    "pointer-events": "",
                    "cursor": ""
                });
                viewUpdate()
            }
        }
    })
};
$("#startTime").on('input', function() {
    if ($("#startTime").val().length == 19) {
        viewUpdate()
    }
});

function preloading() {
    var start = $("#startTimeValue").val();
    var end = $("#endTimeValue").val();
    var startOne = start.substring(0, 19);
    var endOne = end.substring(0, 19);
    var startTwo = new Date(startOne);
    var endTwo = new Date(endOne);
    var continued = parseInt(endTwo - startTwo) / 1000 / 60;
    $("#duration").val(continued);
    $('#calendars').fullCalendar('select', startOne, endOne, true)
}

function continued(obj) {
    var time = $("#duration").val();
    if (obj == "-") {
        if (time == 0) {
            $("#duration").val(0);
            viewUpdate()
        } else {
            $("#duration").val(parseInt(time) - 15);
            viewUpdate()
        }
    } else if (obj == "+") {
        $("#duration").val(parseInt(time) + 15);
        viewUpdate()
    }
}

function viewUpdate() {
    var start = $("#startTime").val();
    var date = new Date(start.replace("-", "/"));
    date.setMinutes(date.getMinutes() + parseInt($("#duration").val()), date.getSeconds(), 0);
    var ends = new Date(date);
    var currentYear = ends.getFullYear();
    var currentMonth = ends.getMonth() + 1;
    var currentDay = ends.getDate();
    var currentHours = ends.getHours();
    var currentMinutes = ends.getMinutes();
    if (currentMonth < 10) currentMonth = "0" + currentMonth;
    if (currentDay < 10) currentDay = "0" + currentDay;
    if (currentHours < 10) currentHours = "0" + currentHours;
    if (currentMinutes < 10) currentMinutes = "0" + currentMinutes;
    var end = currentYear + "-" + currentMonth + '-' + currentDay + ' ' + currentHours + ':' + currentMinutes;
    $('#calendars').fullCalendar('select', start, end, true)
}

function temporaryAppointment() {
    var index = layer.open({
        type: 2,
        title: '添加预约客户',
        area: ['50%', '50%'],
        fix: true,
        maxmin: true,
        content: Feng.ctxPath + '/doctorLooked/temporaryAppointment'
    });
    this.layerIndex = index
}

function refreshChange() {
    document.getElementById('doctorValue').value = $("#doctor").val();
    var doctor = document.getElementById('doctorValue').value;
    var value = $("#startTimeValue").val().substring(0, 10);
    $('#calendars').fullCalendar('refetchEvents');
    $.ajax({
        type: "POST",
        url: Feng.ctxPath + "/doctorLooked/getDoctorStatus",
        data: {
            "doctor": doctor,
            "value": value
        },
        dataType: "json",
        success: function(data) {
            if (data == 2) {
                $('#calendars .fc-time-grid td.fc-day').css("background", "#eeeeee");
                $('#calendars .fc-time-grid').css({
                    "pointer-events": "none",
                    "cursor": "not-allowed"
                })
            } else if (data == 1) {
                $('#calendars .fc-time-grid td.fc-day').css("background", "#FFFFFF");
                $('#calendars .fc-time-grid').css({
                    "pointer-events": "",
                    "cursor": ""
                })
            }
        }
    })
}

function submission() {
    var customerPhone = document.getElementById("customerPhone").innerHTML;
    var fieldTc = document.getElementById("fieldTc").value;
    var doctor = document.getElementById("doctor").value;
    var remarks = document.getElementById("remarks").value;
    var reservationsId = document.getElementById("reservationsId").value;
    var customerId = document.getElementById("customerId").value;
    var treatmentUnit = document.getElementById("treatmentUnit").value;
    var reach = document.getElementById("reach").value;
    var check = $("input[type='checkbox']:checked");
    var startTime = document.getElementById("startTime").value;
    var endTime = document.getElementById("endTimeValue").value;
    var duration = document.getElementById("duration").value;
    var scordd = document.getElementById("scordd").value;
    var projectData = "";
    for (var i = 0; i < check.length; i++) {
        projectData += $(check[i]).val() + ","
    }
    if (treatmentUnit == "" || treatmentUnit == null) {
        alert("请选择科室！");
        return
    }
    var weekEnd = startTime.split(" ")[0] + " 20:00:00";
    if (startTime > weekEnd) {
        alert("预约时间不在医生工作时间内！");
        return
    }
    if (scordd == "sc") {
        $.ajax({
            url: Feng.ctxPath + "/customer/addCustomerMarket",
            type: "post",
            data: {
                "reservationsId": reservationsId,
                "startTimeValue": startTime,
                "customerPhone": customerPhone,
                "customerId": customerId,
                "projectData": projectData,
                "treatmentUnit": treatmentUnit,
                "fieldTc": fieldTc,
                "doctor": doctor,
                "remarks": remarks,
                "duration": duration,
                "isMarketTc": "0"
            },
            success: function(data) {
                if (confirm("是否推送预约消息？")) {
                    $.ajax({
                        url: Feng.ctxPath + "/msgSend/sendAppointmentMessage",
                        type: "post",
                        data: {
                            "treatmentUnit": treatmentUnit,
                            "projectData": projectData,
                            "doctor": doctor,
                            "startTimeValue": startTime,
                            "reservationsId": reservationsId,
                            "customerPhone": customerPhone
                        },
                        success: function(data) {
                            if (data == 1) {
                                Feng.success('发送操作成功!');
                                parent.layer.close(parent.layer.getFrameIndex(window.name))
                            } else {
                                Feng.success('未关注微信服务号!')
                            }
                        },
                    })
                } else {
                    parent.layer.close(parent.layer.getFrameIndex(window.name))
                }
            },
            error: function(data) {
                Feng.success('预约失败!')
            }
        })
    } else {
        if ($("#temporaryValue").val() == '临时') {
            $.ajax({
                url: Feng.ctxPath + "/customer/addTemporaryCustomer",
                type: "post",
                data: {
                    "reservationsId": reservationsId,
                    "startTimeValue": startTime,
                    "customerPhone": customerPhone,
                    "customerId": customerId,
                    "projectData": projectData,
                    "treatmentUnit": treatmentUnit,
                    "fieldTc": fieldTc,
                    "doctor": doctor,
                    "remarks": remarks,
                    "duration": duration
                },
                success: function(data) {
                    Feng.success('预约成功!');
                    window.parent.$('#calendar').fullCalendar('refetchEvents');
                    if (confirm("是否推送预约消息？")) {
                        $.ajax({
                            url: Feng.ctxPath + "/msgSend/sendAppointmentMessage",
                            type: "post",
                            data: {
                                "treatmentUnit": treatmentUnit,
                                "projectData": projectData,
                                "doctor": doctor,
                                "startTimeValue": startTime,
                                "reservationsId": reservationsId,
                                "customerPhone": customerPhone
                            },
                            success: function(data) {
                                if (data == 1) {
                                    Feng.success('发送操作成功!');
                                    parent.layer.close(parent.layer.getFrameIndex(window.name))
                                } else {
                                    Feng.success('未关注微信服务号!')
                                }
                            },
                        })
                    } else {
                        parent.layer.close(parent.layer.getFrameIndex(window.name))
                    }
                },
                error: function(data) {
                    Feng.success('预约失败!')
                }
            })
        } else {
            if (reach == "" || reach == null) {
                alert("患者未输入！");
                return
            }
            $.ajax({
                url: Feng.ctxPath + "/customer/addCustomerFzs",
                type: "post",
                data: {
                    "reservationsId": reservationsId,
                    "startTimeValue": startTime,
                    "endTimeValue": endTime,
                    "customerPhone": customerPhone,
                    "customerId": customerId,
                    "projectData": projectData,
                    "treatmentUnit": treatmentUnit,
                    "fieldTc": fieldTc,
                    "doctor": doctor,
                    "remarks": remarks,
                    "duration": duration,
                    "isFz": "2"
                },
                success: function(data) {
                    var ids = data.ids;
                    if (data.status == 1) {
                        window.parent.register(data)
                    }
                    if (ids == 11) {
                        alert('预约时间必须大于当前时间!')
                    } else {
                        Feng.success('预约成功!');
                        window.parent.$('#calendar').fullCalendar('refetchEvents');
                        parent.layer.close(parent.layer.getFrameIndex(window.name))
                    }
                },
                error: function(data) {
                    Feng.success('预约失败!')
                }
            })
        }
    }
}
var pageStart = 1;
var pageSize = 10;
var request;

function searchDate() {
    if ($("#reach").val() == "") {
        $("#dataBox").hide();
        return
    }
    if (request != null) {
        request.abort()
    }
    request = $.ajax({
        url: Feng.ctxPath + "/customer/getCustomerByReachNew",
        type: "post",
        data: {
            reach: $("#reach").val(),
            pageStart: pageStart,
            pageSize: pageSize
        },
        success: function(datas) {
            var data = datas.customerInfoList;
            $("#dataBox").show();
            var patient = "";
            for (var i = 0; i < data.length; i++) {
                patient += '<div style="padding: 5px 10px;border-bottom: 1px solid #cccccc;display: flex" id="' + data[i].reservationsId + '" class="cuttitle">' +
                    '<div class="scordd" id="' + datas.scordd + '"></div>' +
                    '<div style="flex: 1.2"><img src="' + data[i].customerSexHead  + '" alt="" width="50px;"></div>' +
                    '<div style="flex: 3">' +
                    '<div style="line-height: 20px;"><span>' + data[i].customerName + '</span>' +
                    '<span style="margin-left: 10px;">' + data[i].sex + '</span>' +
                    '<span style="margin-left: 10px;">' + data[i].customerAge + '岁</span></div>' +
                    '<div style="line-height: 20px;">' + data[i].customerPhone + '</div>' +
                    '<div style="line-height: 20px;">' + data[i].arrivalStore + '</div>' +
                    '</div></div>'
            }
            $("#dataUl").html(patient);
            if ((pageStart * pageSize) > data.length) {
                $(".js-load-more").hide()
            } else {
                $(".js-load-more").show()
            }
        }
    })
}
$(document).on('click', '.js-load-more', function() {
    pageStart++;
    search()
});
$(document).click(function() {
    $("#dataBox").hide()
});
$("#dataUl").on('click', '.cuttitle', function() {
    var reservationsId = $(this).attr('id');
    var scordd = $(this).find(".scordd").attr('id');
    if (scordd == "dd") {
        $.ajax({
            url: Feng.ctxPath + "/customer/getCustomerByReservationsId/" + reservationsId,
            type: "post",
            success: function(data) {
                document.getElementById("customerId").value = data.id;
                document.getElementById("reservationsId").value = data.reservationsId;
                document.getElementById("customerName").innerHTML = data.customerName;
                document.getElementById("customerAge").innerHTML = data.customerAge;
                document.getElementById("customerPhone").innerHTML = data.customerPhone;
                document.getElementById("customerSex").innerHTML = data.sex;
                document.getElementById("firstVisitDate").innerHTML = data.firstVisitDate;
                document.getElementById("scordd").value = "dd";
                var seletesfieldTc = data.fieldTc;
                if (seletesfieldTc != "" && seletesfieldTc != null) {
                    $("#fieldTc option[value='" + seletesfieldTc + "']").attr("selected", "selected")
                }
                var seletetreatmentUnit = data.treatmentUnit;
                if (seletetreatmentUnit != "" && seletetreatmentUnit != null) {
                    $("#treatmentUnit option[value='" + seletetreatmentUnit + "']").attr("selected", "selected")
                }
                document.getElementById("reach").value = data.customerName;
                $("#dataBox").hide()
            }
        })
    } else if (scordd == "sc") {
        $.ajax({
            url: Feng.ctxPath + "/customer/getReservationsByReservationsId/" + reservationsId,
            type: "post",
            success: function(data) {
                document.getElementById("reservationsId").value = data.id;
                document.getElementById("customerName").innerHTML = data.customerName;
                document.getElementById("customerAge").innerHTML = data.customerAge;
                document.getElementById("customerPhone").innerHTML = data.customerPhone;
                document.getElementById("customerSex").innerHTML = data.sex;
                document.getElementById("reach").value = data.customerName;
                document.getElementById("scordd").value = "sc";
                $("#dataBox").hide()
            }
        })
    }
});